package fhfl.mobapp.belastungstest.mobapp_communicate;

import android.app.Activity;
import android.widget.Toast;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.nio.ByteBuffer;

import fhfl.mobapp.belastungstest.mobapp_belastungstest.MainActivity;

/**
 * Created by ViceBrot on 08.06.2014.
 */
public class ReceiveUDPThread extends Thread
{
    private int port;
    private Boolean isRunning;
    DatagramSocket socket;
    private Activity activity;

    public ReceiveUDPThread(int port, Activity activity) throws IOException
    {
        this.port = port;
        this.activity = activity;
    }

    public void run()
    {
        this.isRunning = true;

        try
        {
            socket = new DatagramSocket(this.port);

            while(isRunning)
            {
                DatagramPacket packet = receive();

                byte[] data = packet.getData();
                final int latency = (int) ((double)(ByteBuffer.wrap(data, 0, MagicNumbers.DATE_LENGTH).getLong() - System.currentTimeMillis())/(double)2);
                final int packetNumber = ByteBuffer.wrap(data, MagicNumbers.DATE_LENGTH, MagicNumbers.PACKET_NUMBER_LENGTH).getInt();
                final int packetSize = (int)((double) data.length / (double) 1024);

                activity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (activity instanceof MainActivity)
                            ((MainActivity)activity).updateData(latency, packetSize, packetNumber);
                    }
                });

            }
            socket.close();
        }
        catch(Exception e)
        {

        }

    }
    public void finish()
    {
        this.isRunning = false;
    }

    private DatagramPacket receive() throws IOException
    {
        byte [] buffer = new byte[65535];
        DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
        socket.receive(packet);
        return packet;
    }
}
